package com.dreamland.dreamland_platform.aspect;

import com.dreamland.dreamland_platform.annotation.Checked;
import com.dreamland.dreamland_platform.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Author Yinyunpeng
 * @Date 2022/4/29 17:33
 * @Version 1.0
 * @Project dreamLand_platform
 */


@Slf4j
@Aspect
@Component
@Order(-1024)
public class WebSecurityAspect {



    @Pointcut("@annotation(com.dreamland.dreamland_platform.annotation.Checked)")
    public void pointcut() {
    }


    @Around("pointcut() && @annotation(checked)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, Checked checked) throws Throwable {
        try {
            //执行前
            Object[] args = proceedingJoinPoint.getArgs();
            //解析参数
            Integer timeout = CommonUtils.getIntegerValue(getMethodParam(args, proceedingJoinPoint, "timeout"), -1);
            String methodName = proceedingJoinPoint.getSignature().getName();
            Object result = proceedingJoinPoint.proceed();
            //执行后
            log.info("调用结束");
            return result;
        } catch (Exception e) {
            log.info("日志打印出错...");
            throw e;
        }
    }


    private Object getMethodParam(Object[] args, ProceedingJoinPoint proceedingJoinPoint, String key) {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取参数名称
        String[] parameterNames = methodSignature.getParameterNames();
        //获取参数名
        int deviceIdIndex = ArrayUtils.indexOf(parameterNames, key);
        Object deviceId = null;
        //通过参数 Index 获取参数信息
        if (deviceIdIndex != -1) {
            deviceId = args[deviceIdIndex];
        }
        return deviceId;
    }

}
